<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>
    
    <!-- 错误状态 -->
    <div v-if="error" class="error">{{ error }}</div>
    
    <!-- 数据为空状态 -->
    <div v-if="!loading && !error && productarr.length === 0" class="empty">
      暂无农产品数据
    </div>
    
    <!-- 数据展示 -->
    <div v-if="!loading && !error && productarr.length > 0" class="content3">
        <ProductVue v-for="(product, index) in productarr" :key="index" :productinfo="product"/>
    </div>
  </div>
</template>

<script setup>

import { ref, onMounted } from 'vue'
import { listArchive } from '@/api/ncpsy/management/archive'
import ProductVue from './ProductVue.vue'

const productarr = ref([])
const loading = ref(false)
const error = ref('')
const loadArchiveData = async () => {
  loading.value = true
  error.value = ''
  try {
      const response = await listArchive({
        currentStatus:'已上架'
      })
    
    // 动态字段映射，适应不同的API响应结构
    const allProducts = (response.rows || []).map(item => {
      const img = item.cropImage || '/default-product.jpg'
      const name = item.cropName || item.variety || '未知产品'
      const address = item.plantingLocation || '未知产地'
      const number = item.traceabilityCode || '无溯源编号'
      const primaryId = item.primaryId || 'null'
      return { img, name, address, number, primaryId }
    })
    
    // 最多展示8条数据
    productarr.value = allProducts.slice(0, 8)
  } catch (err) {
    console.error('获取农产品档案数据失败:', err)
    error.value = '数据加载失败，请稍后重试'
    productarr.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadArchiveData()
})
</script>

<style scoped>
.content3{
    width: 100%;
    height: auto;
    min-height: 530px;
    margin: 50px 0;
    padding: 20px;
    box-sizing: border-box;

    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    justify-items: center;
    overflow-x: hidden;
}

.loading,
.error,
.empty {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
    font-size: 18px;
    color: #666;
}

.error {
    color: #f56c6c;
}

.empty {
    color: #909399;
}
</style>